using System;
using System.Runtime.Serialization;

namespace SearchTools.Exceptions
{
    /// <summary>
    /// Application exception class
    /// </summary>
    [Serializable]
    public class SearchToolsException : ApplicationException
    {
        /// <summary>
        /// Overloaded. Default Constructor.
        /// </summary>
        public SearchToolsException()
        {
        }

        /// <summary>
        /// Overloaded. Initializes a new SearchToolsException with the specified message.
        /// </summary>
        /// <param name="msg">Exception message.</param>
        public SearchToolsException(string msg) : base(msg)
        {
        }

        /// <summary>
        /// Overloaded. Initializes a new SearchToolsException with the specified message and inner exception.
        /// </summary>
        /// <param name="msg">Exception message.</param>
        /// <param name="inner">Inner exception.</param>
        public SearchToolsException(string msg, Exception inner) : base(msg, inner)
        {
        }

        /// <summary>
        /// Deserialization constructor.
        /// </summary>
        /// <param name="info">Holds all of the data needed to serialize or deserialize an object.</param>
        /// <param name="context">The source and destination of a given serialized stream.</param>
        protected SearchToolsException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }

        /// <summary>
        /// Returns the first exception information in an exception's stack trace.
        /// </summary>
        /// <param name="e">The exception.</param>
        /// <returns>The first line in the stack trace.</returns>
        public static string GetFirstExceptionMessage(Exception e)
        {
            if (null == e)
                return null;
            Exception firstException = e;
            while (firstException.InnerException != null)
                firstException = firstException.InnerException;
            string firstLineStackTrace = firstException.StackTrace.IndexOf(Environment.NewLine) > -1
                                             ? firstException.StackTrace.Substring(0,
                                                                                   firstException.StackTrace.IndexOf(
                                                                                       Environment.NewLine))
                                             : firstException.StackTrace;
            return firstException.Message + "\r\n" + firstLineStackTrace;
        }
    }
}